# coding: utf-8

import numpy as np
import pandas as pd

import src.core.CacheUtils as CacheUtils
import src.core.PandasUtils as PandasUtils

train_data = CacheUtils.load_model("../../data/train_data_full.pkl")
columns = train_data["X"].columns

transformer = CacheUtils.load_model("../../data/tf_dif_trans.pkl")

model = CacheUtils.load_model("../../data/xgb_model.pkl")


def classifier(text):
    arr1 = PandasUtils.convert2KeywordsArr(columns, transformer, text)
    y_pre = model.predict(arr1)
    return y_pre[0]


def predict():
    y_pre = model.predict(np.array(train_data["X"]))
    y_val = train_data["y"]
    import sklearn.metrics as metrics

    print("Classification report for classifier: ", metrics.classification_report(y_val, y_pre))
    print("Confusion matrix: ", metrics.confusion_matrix(y_val, y_pre))
    print("accuracy_score: ", metrics.accuracy_score(y_val, y_pre))


def predict_train_csv(test_data):
    y_val = []
    y_pre = []
    for value in test_data.values:
        class_type = classifier(value[1]) + 1
        y_pre.append(class_type)
        y_val.append(value[0])

    import sklearn.metrics as metrics

    print("Classification report for classifier: ", metrics.classification_report(y_val, y_pre))
    print("Confusion matrix: ", metrics.confusion_matrix(y_val, y_pre))
    print("accuracy_score: ", metrics.accuracy_score(y_val, y_pre))

    return y_pre


def predict_test_csv(test_data):
    # print(test_data.head(2))
    result = []
    for value in test_data.values:
        class_type = classifier(value[1]) + 1
        # print("index: ", value[0])
        # print("text: ", value[1])
        # print("type: ", class_type)
        result.append([value[0], class_type])

    # print(result)
    df = pd.DataFrame(data=result, columns=["index", "type"])
    return df


def main():
    print("predict default")
    predict()

    print("predict training csv")
    # 模型中去掉了第一行，这里也去掉
    predict_train_csv(pd.read_csv("../../data/training.csv"))

    print("predict and save testing csv")
    df = predict_test_csv(pd.read_csv("../../data/testing.csv", header=None))
    df.to_csv("../../data/testing_result.csv", index=False)


if __name__ == '__main__':
    import sys

    # print(sys.argv)
    if sys.argv.__len__() == 2:
        # print(sys.argv[1])
        value = classifier(sys.argv[1])
        print(value)
    else:
        print("execute predict and save csv")
        main()
